<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;


use AlibabaCloud\SDK\Imm\V20200930\Models\InputFile\figures;
use app\admin\model\FigureUser;
use app\admin\model\IntelligenceChangeHair;
use app\admin\model\IntelligenceFaceTransplant;
use app\admin\model\IntelligenceHandheldProduct;
use app\admin\model\IntelligenceHighDefinition;
use app\admin\model\IntelligenceLog;
use app\admin\model\IntelligenceOldImageRepaire;
use app\admin\model\IntelligenceReplacement;
use app\admin\model\IntelligenceSeparateAudio;
use app\admin\model\IntelligenceWenshengPicture;
use app\BaseController;
use app\common\service\AgentApiService;
use app\common\service\ApiService;
use Firebase\JWT\JWT;
use OSS\OssClient;
use think\App;

/**
 * 形象克隆操作
 *
 * @author Administrator
 *
 */
class Intelligence extends BaseController
{

    protected $hair = [
        [
             'img' => '/hair/1301.png',
             'name' => '补发缝'
             ,'code' => '1301'
         ],
        [
            'img' => '/hair/1101.png',
            'name' => '补发际线'
            ,'code' => '1101'
        ],
        [
            'img' => '/hair/603.png',
            'name' => '短发'
            ,'code' => '603'
        ],
       [
            'img' => '/hair/801.png',
            'name' => '金发'
            ,'code' => '801'
        ],
      [
            'img' => '/hair/301.png',
            'name' => '刘海加长发'
            ,'code' => '301'
        ],
      [
            'img' => '/hair/101.png',
            'name' => '刘海'
            ,'code' => '101'
        ],

       [
            'img' => '/hair/502.png',
            'name' => '轻程度卷发'
            ,'code' => '502'
        ],
      [
            'img' => '/hair/402.png',
            'name' => '轻程度增发',
            'code' => '402'
        ],

         [
            'img' => '/hair/1001.png',
            'name' => '头发去油',
            'code' => '1001'
        ],
       [
            'img' => '/hair/1201.png',
            'name' => '头发柔顺',
            'code' => '1201'
        ],
      [
            'img' => '/hair/201.png',
            'name' => ' 长发',
            'code' => '201'
        ],
        [
            'img' => '/hair/901.png',
            'name' => '直发',
            'code' => '901'
        ],
       [
            'img' => '/hair/401.png',
            'name' => ' 中程度增发',
            'code' => '401'
        ],

       [
            'img' => '/hair/503.png',
            'name' => '重程度卷发',
            'code' => '503'
        ],
        [
            'img' => '/hair/403.png',
            'name' => '重程度增发',
            'code' => '403'
        ],
        ];
    /**
     * 文生图
     * @throws \OSS\Core\OssException
     */
    public function wenshengPicture()
    {

        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'wensheng_picture');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }


        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();
        }
        $data = [
            'sex' => isset($param['sex']) ? $param['sex'] : 0,
            'age' => isset($param['age']) ? $param['age'] : 0,
            'colour_skin' => isset($param['colour_skin']) ? $param['colour_skin'] : 0,
            'desc' => $param['desc'],
            'uid' => $param['uid'],
            'title' => $param['title'],
            'type' => $param['type']
        ];
        $wenshengPicture = new IntelligenceWenshengPicture();
        $result = $apiService->wenshengPicture($data);
        if ($result['code'] == 1) {
            $imgFileName = time() . uniqid() . '.png';

            //  if (!$ossClientUpload->doesObjectExist(sysconfig('upload', 'alioss_bucket'), $imgFileName)) {
            $imgDownloadPath = root_path() . 'public/' . $imgFileName;
            $ch = curl_init($result['data']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $imgData = curl_exec($ch);
            curl_close($ch);
            // 将视频数据保存到本地文件
            $imgFile = fopen($imgDownloadPath, 'wb');
            fwrite($imgFile, $imgData);
            fclose($imgFile);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $uploadimgUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), time() . $imgFileName, $imgDownloadPath);

            $imgSrc = $uploadimgUrl['info']['url'];
            // 上传阿里云后删除
            unlink($imgDownloadPath);
            $log_no = getPayNo('wsp');
            if ($param['type'] == 1){
                user_balance_used($param['uid'], $log_no, 2, 51, 1);
            }else{
                user_balance_used($param['uid'], $log_no, 2, 50, 1);
            }

            $data['return_result'] = $imgSrc;
            $data['log_no'] = $log_no;
            $wenshengPicture->save($data);
            return result(0, '生成成功', $wenshengPicture);
        } else {

            return result(-1, '生成失败');
        }
    }

    /**
     * 文生图 列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wenshengPictureList()
    {

        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceWenshengPicture();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));

        $where = [];

        $where[] = ['uid','=',$param['uid']];





     //   $where['uid']=  $param['uid'];
        if ($param['type']){
            $where[] = ['type','=',$param['type']];

        }
        if ($param['tabsId']){
            if ($param['tabsId'] == 1){
                $where[] = ['type','in',[1,2]];
            }else{
                $where[] = ['type','in',[3,4]];
            }

        }


        $total = $wenshengPicture->where($where )->count();
        $list = $wenshengPicture->where($where)->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    /**
     * 图片换转
     */
    public function replacement()
    {
        $request = $this->request;
        $param = $request->param();

        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'img_replacement');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();
        }
        $data = [
            'model_url' => $param['model_url'],
            'uid' => $param['uid'],
            'garmen_url' => json_encode($param['garmen_url']),
            'title' => $param['title'],
        ];
        $params['model_url'] =$param['model_url'];
        $params['garmen_url'][0]['url'] =$param['garmen_url']['url'];
        $params['garmen_url'][0]['type'] =$param['garmen_url']['type'];
        $result = $apiService->replacement($params);
        if ($result['code'] == 1) {

            $IntelligenceReplacement = new IntelligenceReplacement();
            $data['task_id'] = $result['data']['task_id'];
            $log_no = getPayNo('re');
            $data['log_no'] = $log_no;
            user_balance_used($param['uid'], $log_no, 2, 33, 1);
            $wenshengPictureInfo = $IntelligenceReplacement->save($data);
            //$wenshengPicture->where(['id'=> $wenshengPicture->id])->update(['img'=>$imgSrc]);
            return result(0, '生成成功', ["task_id" => $result['data']['task_id'], 'id' => $IntelligenceReplacement->id]);
        } else {

            return result(-1, '生成失败');
        }
    }

    public function replacementSelect()
    {
        $request = $this->request;
        $param = $request->param();
        $IntelligenceReplacement = new IntelligenceReplacement();
        $wenshengPictureInfo = $IntelligenceReplacement->where(['id' => $param['id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->replacementSelect(['task_id' => $wenshengPictureInfo['task_id']]);
        if (isset($result['code']) && $result['code'] == 1) {
            $IntelligenceReplacement->where(['id' => $param['id']])->update(['img' => $result['data']]);
            // tally_deduct($account_id, 30, 1, '');
            return result(0, '生成成功', ['img' => $result['data']]);
        } else if ($result['code'] == 400) {
            return result(-3, '等待生成中');
        } else {
            return result(-1, $result['msg']);
        }
    }

    public function replacementList()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceReplacement();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' => $param['uid']])->count();
        $list = $wenshengPicture->where(['uid' => $param['uid']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * 老照片修复
     */
    public function oldImageRepair()
    {
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'old_image_repair');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();
        }
        $img['image_urls'][] = $param['image_url'];
        $result = $apiService->oldImageRepair($img);
        if ($result['code'] == 1) {
            $IntelligenceOldImageRepaire = new IntelligenceOldImageRepaire();
            $log_no = getPayNo('oir');

            $data = [
                'image_url' => $param['image_url'],
                'uid' => $param['uid'],
                'title' => $param['title'],
                'return_img' => $result['data']

            ];
            $data['log_no'] = $log_no;
            $IntelligenceOldImageRepaire->save($data);
            user_balance_used($param['uid'], $log_no, 2, 34, 1);
            //$wenshengPictureInfo = $IntelligenceReplacement->save($data);
            //$wenshengPicture->where(['id'=> $wenshengPicture->id])->update(['img'=>$imgSrc]);
            return result(0, '生成成功', $IntelligenceOldImageRepaire);
        } else {

            return result(-1, '生成失败');
        }

    }

    public function oldImageList()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceOldImageRepaire();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' => $param['uid']])->count();
        $list = $wenshengPicture->where(['uid' => $param['uid']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * ai 换脸
     */
    public function faceTransplant()
    {
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'face_transplant');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $image_urls['image_urls'] = explode(',',$param['image_urls']);
        $result = $apiService->faceTransplant($image_urls);
        if ($result['code'] == 1) {
            $IntelligenceReplacement = new IntelligenceFaceTransplant();
            $log_no = getPayNo('ft');
            $data = [
                'image_urls' => $param['image_urls'],
                'uid' => $param['uid'],
                'title' => $param['title'],
                'return_img' => $result['data']
            ];
            $data['log_no'] = $log_no;
            $IntelligenceReplacement->save($data);
            user_balance_used($param['uid'], $log_no, 2, 35, 1);
            return result(0, '生成成功', $IntelligenceReplacement);
        } else {
            return result(-1, '生成失败');
        }
    }


    public function faceTransplantList()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceFaceTransplant();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' => $param['uid']])->count();
        $list = $wenshengPicture->where(['uid' => $param['uid']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function changeHair()
    {
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'change_hair');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }

        $params['image_urls'][0] = $param['image_urls'];
        $params['hair_type'] = (int)$param['hair_type'];
        $result = $apiService->changeHair($params);
        if ($result['code'] == 1) {
            $IntelligenceReplacement = new IntelligenceChangeHair();
            $log_no = getPayNo('ft');
            $data = [
                'image_urls' => $param['image_urls'],
                'uid' => $param['uid'],
                'title' => $param['title'],
                'hair_type' => $param['hair_type'],
                'return_img' => $result['data']
            ];
            $data['log_no'] = $log_no;

            $IntelligenceReplacement->save($data);
            user_balance_used($param['uid'], $log_no, 2, 36, 1);
            return result(0, '生成成功', $IntelligenceReplacement);
        } else {
            return result(-1, '生成失败');
        }
    }

    public function changeHairList()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceChangeHair();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' => $param['uid']])->count();
        $list = $wenshengPicture->where(['uid' => $param['uid']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


    public function imgEdit()
    {
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'composite_image');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }


        $result = $apiService->imgEdit($param);
        if ($result['code'] == 1) {
            $IntelligenceReplacement = new IntelligenceChangeHair();
            $log_no = getPayNo('ft');
            /*  $data =[
                  'image_urls' =>  $param['image_urls'],
                  'uid' =>  $param['uid'],
                  'title'=> $param['title'],
                  'hair_type' => $param['hair_type'],
                  'return_img' => $result['data']
              ];

              $IntelligenceReplacement->save($data);*/
            //  user_balance_used($param['uid'], $log_no, 2, 40,1);
            return result(0, '生成成功', $result);
        } else {
            return result(-1, '生成失败');
        }
    }

    public function highDefinition()
    {
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'high_definition_img');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $params['image_urls'][0] = $param['image_url'];
        $result = $apiService->highDefinition($params);
        if ($result['code'] == 1) {
            $IntelligenceReplacement = new IntelligenceHighDefinition();
            $log_no = getPayNo('hd');
            $data = [
                'image_urls' => $param['image_url'],
                'uid' => $param['uid'],
                'title' => $param['title'],
                'return_img' => $result['data']
            ];
            $IntelligenceReplacement->save($data);
            $data['log_no'] = $log_no;
            user_balance_used($param['uid'], $log_no, 2, 37, 1);
            return result(0, '生成成功', $result);
        } else {
            return result(-1, '生成失败');
        }
    }


    public function highDefinitionList()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceHighDefinition();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' => $param['uid']])->count();
        $list = $wenshengPicture->where(['uid' => $param['uid']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function separateAudio()
    {
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'separate_audio');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }


        $result = $apiService->separateAudio($param);
        if ($result['code'] == 1) {
            $IntelligenceReplacement = new IntelligenceSeparateAudio();
            $log_no = getPayNo('sa');
            $data = [
                'video_url' => $param['video_url'],
                'uid' => $param['uid'],
                'title' => $param['title'],
                'job_id' => $result['data'],
            ];

            $IntelligenceReplacement->save($data);
            $data['log_no'] = $log_no;
            user_balance_used($param['uid'], $log_no, 2, 38, 1);
            return result(0, '生成成功', $IntelligenceReplacement);
        } else {
            return result(-1, '生成失败');
        }
    }

    public function separateAudioResult()
    {
        $request = $this->request;
        $param = $request->param();
        $IntelligenceReplacement = new IntelligenceSeparateAudio();

        $IntelligenceReplacementInfo = $IntelligenceReplacement->where(['id' => $param['id']])->find();

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->separateAudioResult(['jobid' => $IntelligenceReplacementInfo['job_id']]);
        if ($result['code'] == 1) {
            $audio = time() . uniqid() . '.mp3';
            $audioDownloadPath = root_path() . 'public/' . $audio;
            $ch = curl_init($result['data']['audio']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $imgData = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if ($httpCode == 404){
                return result(-3, '生成中');
            }
            // 将视频数据保存到本地文件
            $imgFile = fopen($audioDownloadPath, 'wb');
            fwrite($imgFile, $imgData);
            fclose($imgFile);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $uploadaudioUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), time() . $audio, $audioDownloadPath);

            $audioSrc = $uploadaudioUrl['info']['url'];
            // 上传阿里云后删除
            unlink($audioDownloadPath);

            //  $result['data']['audioBackgroud'];

            $audioBackgroud = time() . uniqid() . '.mp3';
            $audioBackgroudDownloadPath = root_path() . 'public/' . $audioBackgroud;
            $ch = curl_init($result['data']['audioBackgroud']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $audioBackgroudData = curl_exec($ch);
            curl_close($ch);
            // 将视频数据保存到本地文件
            $audioBackgroudFile = fopen($audioBackgroudDownloadPath, 'wb');
            fwrite($audioBackgroudFile, $audioBackgroudData);
            fclose($audioBackgroudFile);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $uploaudioBackgroudUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), time() . $audioBackgroud, $audioBackgroudDownloadPath);

            $audioBackgroudSrc = $uploaudioBackgroudUrl['info']['url'];
            // 上传阿里云后删除
            unlink($audioBackgroudDownloadPath);



            $IntelligenceReplacement->where(['id' => $param['id']])->update([
                'audio' => $audioSrc,
                'audio_backgroud' =>$audioBackgroudSrc,
            ]);
            $IntelligenceReplacementInfo = $IntelligenceReplacement->where(['id' => $param['id']])->find();
            return result(0, '生成成功', $IntelligenceReplacementInfo);
        } else {
            return result(-1, '生成失败');
        }
    }

    public function imgGenerateVideo()
    {

        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'img_generate_video');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $data = [
            'desc' => $param['desc'],
            'uid' => $param['uid'],
            'title' => $param['title'],
            'type' => $param['type'],

        ];
        if (isset($param['img'])){
            $data['img'] = $param['img'];
            $body['image_urls'] = $data['img'];
        }
        if (isset($param['base_img']) && $param['base_img'] ){
            /* $data['base_img'] = $param['base_img'];
            $body['image_urls'] = 'data:image/png;base64,'.$data['base_img'];*/
            $imageData = base64_decode($param['base_img']);
            $videoDownloadPath = root_path() . 'public/' . time().uniqid().'.png';
            file_put_contents($videoDownloadPath, $imageData);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $videoFileName = basename($videoDownloadPath);
            $uploadVideoUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), $videoFileName, $videoDownloadPath);
            $videoInfo['result'] = $uploadVideoUrl['info']['url'];
            $data['img'] = $uploadVideoUrl['info']['url'];
            $body['image_urls'] = $uploadVideoUrl['info']['url'];
            unlink($videoDownloadPath);
            //   $data['img'] = $param['img'];
        }

        $body['prompt'] = $data['desc'];
        $body['type'] = $data['type'];
        $wenshengPicture = new IntelligenceWenshengPicture();
        $result = $apiService->imgGenerateVideo($body);
        if ($result['code'] == 1) {
            $log_no = getPayNo('igv');
            $data['task_id'] = $result['data'];
            $data['log_no'] = $log_no;
            if ( $param['type']== 3){
                user_balance_used($param['uid'], $log_no, 2, 39, 1);
            }else{
                user_balance_used($param['uid'], $log_no, 2, 52, 1);
            }

            $wenshengPicture->save($data);
            return result(0, '生成成功', $wenshengPicture);
        } else {

            return result(-1, '生成失败');
        }
    }

    public function imgGenerateVideoSelect()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceWenshengPicture();
        $wenshengPictureInfo = $wenshengPicture->where(['id' => $param['id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->imgGenerateVideoSelect(['task_id' => $wenshengPictureInfo['task_id']]);

        if ($result['code'] == 1) {
            $imgFileName = time() . uniqid() . '.mp4';
            $imgDownloadPath = root_path() . 'public/' . $imgFileName;
            $ch = curl_init($result['data']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $imgData = curl_exec($ch);
            curl_close($ch);
            // 将视频数据保存到本地文件
            $imgFile = fopen($imgDownloadPath, 'wb');
            fwrite($imgFile, $imgData);
            fclose($imgFile);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $uploadimgUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), time() . $imgFileName, $imgDownloadPath);
            $imgSrc = $uploadimgUrl['info']['url'];
            // 上传阿里云后删除
            unlink($imgDownloadPath);
            $data['return_result'] = $imgSrc;
            $wenshengPicture->where(['id' => $param['id']])->save($data);
            return result(0, '生成成功', $wenshengPictureInfo);
        } else if ($result['code'] == 1001) {
            return result(-1, '生成失败');
        } else if ($result['code'] == 1002) {

            return result(-3, '生成中');
        }

    }

    public function separateAudioList()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceSeparateAudio();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' => $param['uid']])->count();
        $list = $wenshengPicture->where(['uid' => $param['uid']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function hairList(){
       $hair  =  $this->hair;
       foreach ($hair as $key => $value){
           $hair[$key]['img'] = 'https://' . $_SERVER['HTTP_HOST'].$value['img'];
       }
        return result(0, 'success',$hair);
    }

    public  function oauth(){
        $request = $this->request;
        $param = $request->param();
        $Intelligence  = new \app\admin\model\Intelligence();
        $IntelligenceInfo  = $Intelligence->where(['id' => $param['id']])->find();
        if ($IntelligenceInfo['authorize_type'] == 3){
            if ( empty($IntelligenceInfo['token']) || $IntelligenceInfo['expires_in'] < time() ){
                $data =  [
                    "iss"=>$IntelligenceInfo['aouth_application_id'], //"1196014988097",   // OAuth 应用的 ID
                    "aud"=> "api.coze.cn",    // 扣子 API 的 Endpoint
                    "iat"=>time(),       // JWT 开始生效的时间，秒级时间戳
                    "exp"=> time()+6000,       // JWT 过期时间，秒级时间戳
                    "jti"=> getNonceStr(10), // 随机字符串，防止重放攻击
                    "session_name"=> "test",  //用户在业务侧的 UID

                ];
                // api_token_expires_in
                $signing_key =     file_get_contents( $IntelligenceInfo['pem'] );
                $headers = $IntelligenceInfo['aouth_public_id'];  # 替换为你的实际 Coze App 公钥指纹
                $jwt = JWT::encode($data ,$signing_key, 'RS256', $headers);
                $header = array(
                    'Content-Type: application/json',
                    'Authorization: Bearer '. $jwt
                );
                $url = 'https://api.coze.cn/api/permission/oauth2/token';
                $params =[
                    'duration_seconds' => 86399,
                    'grant_type'=>'urn:ietf:params:oauth:grant-type:jwt-bearer'
                ];
                $ret  = $this->apiPost($url,$header,$params);
                $result = json_decode($ret, true);
                if (isset($result['error_code'])){
                    return result(-1, '授权失败，请联系管理员'.$result['error_message']);
                }else{
                    $Intelligence->where(['id' => $param['id']])->update([
                        'expires_in' => $result['expires_in'],
                        'token' =>  $result['access_token']]);
                }
            }

        }elseif($IntelligenceInfo['authorize_type'] == 2) {

            if (empty($IntelligenceInfo['api_token'])){
                return result(-1, '请联系管理员,密钥未配置');
            }
            if ( strtotime($IntelligenceInfo['api_token_expires_in']) < time() ){
                return result(-1, '请联系管理员,授权过期');
            }
        }else{
            $siteSet = sysconfig('site');
            if (empty($siteSet['kouzhi_token'])){
                return result(-1, '请联系管理员,密钥未配置');
            }
            if (strtotime($siteSet['kouzhi_expires_in'] )< time() ){
                return result(-1, '请联系管理员,授权过期');
            }
        }
        return result(0, '成功');



    }

    public function workRun()
    {
        $url = 'https://api.coze.cn/v1/workflow/run';
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $Intelligence  = new \app\admin\model\Intelligence();
        $IntelligenceInfo  = $Intelligence->where(['id' => $param['id']])->find();

        $tally = $IntelligenceInfo['points'];
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }
        $params =[];

        foreach ($param['widget_josn'] as $value){
            $params['parameters'][$value['field']] = $value['value'];
        }



       // $params['parameters'] = $param['parameters'];

        if ($IntelligenceInfo['authorize_type'] == 3){
            if ($IntelligenceInfo['expires_in'] < time()){
                return result(-1, '请求授权授权过期');
            }
        }elseif($IntelligenceInfo['authorize_type'] == 2) {
            if (empty($IntelligenceInfo['api_token'])){
                return result(-1, '请联系管理员,密钥未配置');
            }
            if ( strtotime($IntelligenceInfo['api_token_expires_in']) < time() ){
                return result(-1, '请联系管理员,授权过期');
            }
        }else{
            $siteSet = sysconfig('site');
            if (empty($siteSet['kouzhi_token'])){
                return result(-1, '请联系管理员,密钥未配置');
            }
            if (strtotime($siteSet['kouzhi_expires_in'] )< time() ){
                return result(-1, '请联系管理员,授权过期');
            }
        }


        $params['workflow_id'] = $IntelligenceInfo['work_id'];
        $params['is_async'] = true;
        if ($IntelligenceInfo['authorize_type'] == 3){
            $token = $IntelligenceInfo['token'];
        }elseif ($IntelligenceInfo['authorize_type'] == 2){
            $token = $IntelligenceInfo['api_token'];

        }else{
            $siteSet = sysconfig('site');
            if (empty($siteSet['kouzhi_token'])){
                return result(-1, '请联系管理员,密钥未配置');
            }
            $token =$siteSet['kouzhi_token'];
        }
        $header = array(
            'Content-Type: application/json',
            'Authorization: Bearer '. $token
        );
        $ret  = $this->apiPost($url,$header,$params);
        $result = json_decode($ret, true);




        if ($result['code'] == 0){
            //$content = (json_decode($result['data']));
            $log_no = getPayNo('it');

                $saveData = [
                    'uid' => $param['uid'],
                    'title' => $param['title'],
                    'points' => $IntelligenceInfo['points'],
                    'parameters' => json_encode($params),
                    'log_no' => $log_no,
                    'status' => 0,
                    'task_id' => $result['execute_id'],
                  //  'output' => $content->output,
                    'intelligence_id' => $param['id']
                ];

            $IntelligenceLog = new IntelligenceLog();
            $IntelligenceLog->save($saveData);
            $Intelligence->where(['id' => $param['id']])->inc('use_number')->update();
                user_balance_used($param['uid'], $log_no, 2, 53, $IntelligenceInfo['points']);
            return result(0, '成功',['execute_id' => $result['execute_id'],'id'=>$IntelligenceLog->id ]);
        }else{
            return result(-1, $result['msg']);
        }

    }

    function apiPost($url, $header, $data = NULL)
    {

        $userAgent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';

        // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 600); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 类型为json
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Error POST' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $result; // 返回数据
    }

    public function intelligenceList(){
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture =  new \app\admin\model\Intelligence();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $where  = [];
        if (isset($param['classid']) && $param['classid'] ){
            $where['class_id']= $param['classid'];
        }
        $total = $wenshengPicture->where(['intelligence.is_display' =>1])->where($where)
            ->withJoin('intelligenceClass', 'LEFT')
            ->count();
        $list = $wenshengPicture->where(['intelligence.is_display' =>1])->where($where)
            ->withJoin('intelligenceClass', 'LEFT')
            ->order('sort', 'desc')
            //->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        foreach ($list as $key => $value){
            $list[$key]['widget_josn'] = json_decode($value['widget_josn']);
        }
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
          //  'pindex' => $pindex,
         //   'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


    public function intelligenceLogList(){
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture =  new \app\admin\model\IntelligenceLog();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' =>$param['uid']])
            ->withJoin('intelligenceInfo', 'LEFT')->count();
        $list = $wenshengPicture->where(['uid' =>$param['uid']])
            ->withJoin('intelligenceInfo', 'LEFT')
            ->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function intelligenceClass()
    {
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture =  new \app\admin\model\IntelligenceClass();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['is_display' =>1])
          ->count();
        $list = $wenshengPicture->where(['is_display' =>1])
            ->order('sort', 'desc')
          //  ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
           // 'pindex' => $pindex,
          //  'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


    public function handheldProduct(){
        $request = $this->request;
        $param = $request->param();

        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'img_generate_video');
        if ($user['balance'] < $tally) {
            return result(-2, '点数不足，请充值');
        }

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->handheldProduct($param);

        $wenshengPicture = new IntelligenceHandheldProduct();
        if ($result['code'] == 1) {
            $data['uid']  = $param['uid'];
            $data['product_img']  = $param['product_img'];
            $data['character_img']  = $param['character_img'];
            $data['title']  = $param['title'];
            $data['generateUuid']  = $result['data']['generateUuid'];
            $wenshengPicture->save($data);
            $log_no = getPayNo('wsp');
            user_balance_used($param['uid'], $log_no, 2, 54, 1);
            return result(0, '生成成功', $wenshengPicture);
        } else if ($result['code'] == 1001) {
            return result(-1,  $request['msg']);
        }else{
            return result(-1, '失败');
        }
    }


    public function handheldSelect(){
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceHandheldProduct();
        $wenshengPictureInfo = $wenshengPicture->where(['id' => $param['id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->handheldSelect(['generateUuid' => $wenshengPictureInfo['generateUuid']]);

        if ($result['code'] == 1) {
            $imgFileName = time() . uniqid() . '.png';
            $imgDownloadPath = root_path() . 'public/' . $imgFileName;
            $ch = curl_init($result['data']['imageUrl']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $imgData = curl_exec($ch);
            curl_close($ch);
            // 将视频数据保存到本地文件
            $imgFile = fopen($imgDownloadPath, 'wb');
            fwrite($imgFile, $imgData);
            fclose($imgFile);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $uploadimgUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), time() . $imgFileName, $imgDownloadPath);
            $imgSrc = $uploadimgUrl['info']['url'];

            // 上传阿里云后删除
            unlink($imgDownloadPath);
            $data['return_result'] = $imgSrc;
            $wenshengPicture->where(['id' => $param['id']])->save($data);
            return result(0, '生成成功', ['retrun_img' =>$imgSrc]);
        } else if ($result['code'] == 1001) {
            return result(-1, '生成失败');
        } else if ($result['code'] == 1002) {

            return result(-3, '生成中');
        }

    }

    public function handheldProductList(){
        $request = $this->request;
        $param = $request->param();
        $wenshengPicture = new IntelligenceHandheldProduct();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $wenshengPicture->where(['uid' => $param['uid']])->count();
        $list = $wenshengPicture->where(['uid' => $param['uid']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }


}
